package com.ebai.product.management.framework.shiro.realm;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AccountException;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.DisabledAccountException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.ebai.product.management.base.utils.Common;
import com.ebai.product.management.base.utils.SysCode;
import com.ebai.product.management.framework.utils.security.ShiroUtils;
import com.ebai.product.management.model.entity.User;
import com.ebai.product.management.service.system.AuthService;
import com.ebai.product.management.service.system.RoleService;
import com.ebai.product.management.service.system.UserService;

public class UserRealm extends AuthorizingRealm{
	
	private static final Logger log = LoggerFactory.getLogger(UserRealm.class);
	
	@Autowired
    private UserService userService;
	
	@Autowired
	private RoleService roleService;
	
	@Autowired
	private AuthService authService;
	
	@Override
	public String getName() {
		// TODO Auto-generated method stub
		return "MyShiroRealm";
	}

	
	/**
	 * 权限认证
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		// TODO Auto-generated method stub
		String userPid = ShiroUtils.getUserId();
		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
		Set<String> permissins = new HashSet<String>();
		Set<String> roles = new HashSet<String>();
		//管理员登录
		if (StringUtils.equals(ShiroUtils.getLoginName(), SysCode.DEFAULT_USER.DEFAULT_SA)) {
			permissins.add("*:*");
			roles = roleService.selectRolesAll();
		}
		//普通用户登录
		else {
			permissins = authService.selectPermsByUserId(userPid);
	        roles = roleService.selectRoleKeys(userPid);
		}
		info.addStringPermissions(permissins);
		info.addRoles(roles);
		
		return info;
	}

	/**
	 * 身份认证
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		// TODO Auto-generated method stub
		UsernamePasswordToken upToken = (UsernamePasswordToken) token;
		String username = upToken.getUsername();
        String oldpassword = "";
        String newpassword = "";
        if (upToken.getPassword() != null) {
        	oldpassword = new String(upToken.getPassword());
        	newpassword = Common.EncryptMD5(oldpassword + SysCode.DEFAULT_USER.SALT, Common.MD5_LX_32);
        }
        
        User user = null;
        try {
            user = userService.queryByLoginName(username, newpassword);
        }
        catch (Exception e) {
            log.info("对用户[" + username + "]进行登录验证..验证未通过{}", e.getMessage());
            throw new AuthenticationException(e.getMessage(), e);
        }
        
        if (null == user) {
			throw new AccountException("登录名称或登录密码错误(或用户不存在)！");
		}else if(StringUtils.equalsIgnoreCase(SysCode.DICT_TYSF.NO, user.getIsEnable())){
			/**
			 * 如果用户的status为禁用。那么就抛出<code>DisabledAccountException</code>
			 */
			throw new DisabledAccountException("当前用户已禁用，请与管理员联系！");
		}else{
			//登录成功
			log.info("身份认证成功，登录用户："+user.getUserName());
		}
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, oldpassword, getName());
        return info;
	}

	/**
     * 清理缓存权限
     */
    public void clearCachedAuthorizationInfo() {
        this.clearCachedAuthorizationInfo(SecurityUtils.getSubject().getPrincipals());
    }
}
